#!/usr/bin/python3
# -*- coding: utf-8 -*-

import logging
import json
from aiohttp import web
from aioweb import corelib

routes = web.RouteTableDef()
module_name = 'blog'


@routes.get('/%s' % module_name)
@corelib.template('blog.html')
async def blog_index(request):
    data = {}
    try:
        params = await corelib.parse_param(request)
        path = params.get('path', '/root')
    except BaseException as e:
        logging.error('\n%s' % corelib.printException(e))
    return data


@routes.get('/%s/items' % module_name)
async def blog_items(request):
    data = {}
    try:
        # params = await corelib.parse_param(request)
        items = await corelib.load_items('Blog')
        data = dict(data, **items)
    except BaseException as e:
        logging.error('\n%s' % corelib.printException(e))
        data['items'] = []
    return web.json_response({'code': 0, 'msg': data})


@routes.post('/%s/export' % module_name)
async def blog_items(request):
    data = {}
    try:
        params = await corelib.parse_param(request)
        ids = params['ids']
        items = await corelib.load_items('Blog', in_={'id': ids})
        data = dict(data, **items)
    except BaseException as e:
        logging.error('\n%s' % corelib.printException(e))
        data['content'] = corelib.printException(e)
    return web.json_response({'code': 0, 'msg': data})


@routes.post('/%s/save' % module_name)
async def blog_save(request):
    data = {}
    try:
        params = await corelib.parse_param(request)
        items = params['items']
        corelib.save('Blog', items)
        items = await corelib.load_items('Blog')
        data = dict(data, **items)
    except BaseException as e:
        logging.error('\n%s' % corelib.printException(e))
        return web.json_response({'code': -1, 'msg': str(e)})
    return web.json_response({'code': 0, 'msg': data})


@routes.post('/%s/delete' % module_name)
async def blog_delete(request):
    data = {}
    try:
        params = await corelib.parse_param(request)
        ids = params['ids']
        corelib.delete('Blog', ids)
        items = await corelib.load_items('Blog')
        data = dict(data, **items)
    except BaseException as e:
        logging.error('\n%s' % corelib.printException(e))
        return web.json_response({'code': -1, 'msg': str(e)})
    return web.json_response({'code': 0, 'msg': data})
